﻿Imports TransportadoraToledoBLL

Public Class frm_cadastro_frotas
    Public objBLL As New VeiculosBLL
    Public objBLLMarcas As New MarcasBLL
    Public objBLLModeos As New ModelosBLL
    Public objBLLCombustivel As New CombustivelBLL
    Public objCV As New CombustiveisVeiculoBLL
    Public controle As String
    Public ultimo, primeiro, atual As Integer
#Region "Métodos"

    Sub carregaPrimeiroUltimo()
        Try
            ultimo = objBLL.localizarPrimeiroUltimo("ultimo")
            primeiro = objBLL.localizarPrimeiroUltimo("primeiro")
            atual = ultimo
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub


    Sub carregaUltimo()
        If (ultimo <> 0) Then
            objBLL.localizar(ultimo)
            If (objBLL.pcodVeiculo <> 0) Then
                carregaCampos()
            End If
        End If
    End Sub
    Sub carregaPrimeiro()
        If (primeiro <> 0) Then
            objBLL.localizar(primeiro)
            If (objBLL.pcodVeiculo <> 0) Then
                carregaCampos()

            End If
        End If
    End Sub

    Sub limpar()
        tbcodigo.Text = ""
        tbcodmarca.Text = ""
        tbmarca.Text = ""
        tbmodelo.Text = ""
        tbcodmodelo.Text = ""
        tbcombustivel.Text = ""
        tbcodcombustivel.Text = ""
        cbstatus.SelectedIndex = -1
        tbplaca.Text = ""
        tbcor.Text = ""
        TBanofab.Text = ""
        tbanomod.Text = ""
        tbcapacidade.Text = ""
        tbcategoria.Text = ""
        tbchassi.Text = ""
        tbconsulta.Text = ""
        dtcadastro.Value = Date.Now
        cbCombustiveis.Items.Clear()

        objBLL.limpar()
    End Sub

    Sub status(ByVal sta As Boolean)

        If (tbcodigo.Text = "" Or controle = "A") Then
            bIncluir.Enabled = sta

            bExcluir.Enabled = sta
            If (tbcodigo.Text = "") Then
                bAlterar.Enabled = False
                bVaPara.Enabled = False
                bPesquisar.Enabled = False
                bExcluir.Enabled = False
            Else
                bExcluir.Enabled = sta
                bPesquisar.Enabled = sta
                bAlterar.Enabled = sta
                bVaPara.Enabled = sta
            End If
            bCancelar.Enabled = Not sta
            bSalvar.Enabled = Not sta
            bPrimeiro.Enabled = sta
            bProximo.Enabled = sta
            bUltimo.Enabled = sta
            bAnterior.Enabled = sta
            gbConteudo.Enabled = Not sta
        Else
            bIncluir.Enabled = sta

            If (tbcodigo.Text = "") Then
                bExcluir.Enabled = False
                bAlterar.Enabled = False
                bVaPara.Enabled = False
                bPesquisar.Enabled = False
            Else
                bExcluir.Enabled = sta
                bAlterar.Enabled = sta
                bVaPara.Enabled = sta
                bPesquisar.Enabled = sta
            End If

            bCancelar.Enabled = Not sta
            bSalvar.Enabled = Not sta

            gbConteudo.Enabled = Not sta
        End If

        If (atual = primeiro And atual = ultimo) Then
            bProximo.Enabled = False
            bUltimo.Enabled = False
            bAnterior.Enabled = False
            bPrimeiro.Enabled = False
        ElseIf (atual = ultimo) Then
            bProximo.Enabled = False
            bUltimo.Enabled = False
            bAnterior.Enabled = True
            bPrimeiro.Enabled = True
        ElseIf (atual = primeiro) Then
            bProximo.Enabled = True
            bUltimo.Enabled = True
            bAnterior.Enabled = False
            bPrimeiro.Enabled = False
        Else
            bProximo.Enabled = True
            bUltimo.Enabled = True
            bAnterior.Enabled = True
            bPrimeiro.Enabled = True

        End If
    End Sub
    Sub carregaPropriedades()

        Try
            If (tbcodigo.Text = "") Then
                objBLL.pcodVeiculo = 0
            Else
                objBLL.pcodVeiculo = tbcodigo.Text
            End If
            objBLL.pcodModelo = tbcodmodelo.Text
            'objBLL.pcodCombustivel = tbcodcombustivel.Text
            objBLL.pCor = tbcor.Text
            objBLL.pPlaca = tbplaca.Text
            objBLL.pCategoria = tbcategoria.Text
            objBLL.pChassi = tbchassi.Text
            objBLL.pCapacidade = tbcapacidade.Text
            objBLL.pData_cadastro = dtcadastro.Text
            objBLL.pAno_fabricacao = TBanofab.Text
            objBLL.pAno_modelo = tbanomod.Text
            If cbstatus.Text = "Ativo" Then
                objBLL.pAtivo_sn = "S"
            ElseIf cbstatus.Text = "Inativo" Then
                objBLL.pAtivo_sn = "N"
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Sub carregaCampos()
        Try
            tbcodigo.Text = objBLL.pcodVeiculo
            tbcor.Text = objBLL.pCor
            tbplaca.Text = objBLL.pPlaca
            tbcategoria.Text = objBLL.pCategoria
            dtcadastro.Text = objBLL.pData_cadastro
            TBanofab.Text = objBLL.pAno_fabricacao
            tbanomod.Text = objBLL.pAno_modelo
            If objBLL.pAtivo_sn = "S" Then
                cbstatus.Text = "Ativo"
            ElseIf objBLL.pAtivo_sn = "N" Then
                cbstatus.Text = "Inativo"
            End If
            tbchassi.Text = objBLL.pChassi
            tbcapacidade.Text = objBLL.pCapacidade
            ''localiza combustivel
            'tbcodcombustivel.Text = objBLLpcodCombustivel
            'objBLLCombustivel.localizar(objBLL.pcodCombustivel)
            tbcombustivel.Text = objBLLCombustivel.ptipo

            ''localiza marcas
            tbcodmarca.Text = objBLL.pcodMarca
            objBLLMarcas.localizar(Integer.Parse(objBLL.pcodMarca))
            tbmarca.Text = objBLLMarcas.pMar_nome

            ''localiza modelos
            tbcodmodelo.Text = objBLL.pcodModelo
            objBLLModeos.localizar(objBLL.pcodModelo)
            tbmodelo.Text = objBLLModeos.pMod_nome
            objCV.localizar(objBLL.pcodVeiculo)
            Dim tab As New DataTable
            Dim linha As DataRow
            Dim comb As CombustivelBLL
            objCV.localizarTodos(objBLL.pcodVeiculo)
            For Each obj As CombustiveisVeiculoBLL In objBLL.plCombustiveis

                linha = tab.NewRow
                linha("Código") = obj.pcomcodigo
                comb = New CombustivelBLL(obj.pcomcodigo)
                linha("Tipo") = comb.ptipo
                tab.Rows.Add(linha)
                tab.AcceptChanges()

            Next
            cbCombustiveis.Items.Add(tab)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub atualizaGrid()
        Try
            dgDados.DataSource = objBLL.localizar(tbconsulta.Text)
            dgDados.Columns(0).HeaderText = "Código"
            dgDados.Columns(1).HeaderText = "Código Modelo"
            dgDados.Columns(2).HeaderText = "Código Combustivel"
            dgDados.Columns(3).HeaderText = "Placa Veiculo"
            dgDados.Columns(4).HeaderText = "Cor"
            dgDados.Columns(5).HeaderText = "Categoria"
            dgDados.Columns(6).HeaderText = "N° Chassi"
            dgDados.Columns(7).HeaderText = "Capacidade"
            dgDados.Columns(8).HeaderText = "Ano"
            dgDados.Columns(9).HeaderText = "Modelo"
            dgDados.Columns(10).HeaderText = "Ativo S/N"
            dgDados.Columns(11).HeaderText = "Data Cadastro"

            dgDados.AllowUserToAddRows = False


        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub frm_cadastro_frotas_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        carregaPrimeiroUltimo()
        carregaUltimo()
        bCancelar_Click(sender, e)
    End Sub

    Private Sub bCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bCancelar.Click
        If (controle = "I") Then
            carregaPrimeiroUltimo()
            carregaUltimo()
        ElseIf (controle = "A") Then
            objBLL.localizar(atual)
            If (objBLL.pcodVeiculo <> 0) Then
                carregaCampos()
                atual = objBLL.pcodVeiculo
            End If
        End If
        controle = ""

        status(True)
    End Sub

    Private Sub bIncluir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bIncluir.Click
        limpar()

        controle = "I"
        status(False)
    End Sub

    Private Sub bAlterar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bAlterar.Click
        controle = "A"

        status(False)
    End Sub

    Private Sub bExcluir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bExcluir.Click
        Try
            If (MessageBox.Show("Deseja excluir?", "", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
                carregaPropriedades()
                objBLL.excluir()
                MessageBox.Show("Excluido com sucesso!")
                limpar()
                carregaPrimeiroUltimo()
                carregaUltimo()
                status(True)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub bSalvar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bSalvar.Click
        Try

            carregaPropriedades()
            If (controle = "I") Then
                objBLL.inserir()
                MessageBox.Show("Incluido com sucesso!")
                limpar()
                carregaPrimeiroUltimo()
                carregaUltimo()
                status(True)
            Else
                objCV.excluirTodos(tbcodigo.Text)
                objBLL.alterar()
                MessageBox.Show("Alterado com sucesso!")

                status(True)
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub bVaPara_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bVaPara.Click
        Dim frm As New frm_VaPara("veiculos")
        frm.ShowDialog()
        If (frm.codigo <> 0) Then
            objBLL.localizar(frm.codigo)
            If (objBLL.pcodVeiculo <> 0) Then
                carregaCampos()
                atual = objBLL.pcodVeiculo
            Else
                MessageBox.Show("Registro Inexistente!")
                bVaPara_Click(sender, e)
            End If
        End If
        status(True)
        frm = Nothing
    End Sub

    Private Sub bPesquisar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bPesquisar.Click
        dgDados.DataSource = Nothing
        If (Me.Location.Y = 212) Then
            gbConsulta.Visible = True
            Me.Location = New System.Drawing.Point(Me.Location.X, Me.Location.Y - 127)
            Me.Size = New Size(737, 752)
        Else
            gbConsulta.Visible = True
            Me.Location = New System.Drawing.Point(Me.Location.X, Me.Location.Y + 127)
            Me.Size = New Size(737, 752)
        End If
        atualizaGrid()
        'Dim frm As New frm_consultas("Clientes")
        'frm.ShowDialog()
        'If (frm.codigo <> 0) Then
        '    objBLL.localizar(frm.codigo)
        '    If (objBLL.pCodigo <> 0) Then
        '        carregaCampos()
        '    End If
        'End If
        'frm = Nothing
    End Sub

    Private Sub bPrimeiro_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bPrimeiro.Click
        carregaPrimeiro()
        atual = primeiro
        status(True)
    End Sub

    Private Sub bAnterior_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bAnterior.Click
        Dim codigo As Integer = objBLL.localizarProxAnterior("anterior", atual)
        objBLL.localizar(codigo)
        If (objBLL.pcodVeiculo <> 0) Then
            carregaCampos()
            atual = objBLL.pcodVeiculo
        End If
        status(True)
    End Sub

    Private Sub bProximo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bProximo.Click
        Dim codigo = objBLL.localizarProxAnterior("proximo", atual)
        objBLL.localizar(codigo)
        If (objBLL.pcodVeiculo <> 0) Then
            carregaCampos()
            atual = objBLL.pcodVeiculo
        End If
        status(True)
    End Sub

    Private Sub bUltimo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bUltimo.Click
        carregaUltimo()
        atual = ultimo
        status(True)
    End Sub

    Private Sub bAjuda_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bAjuda.Click
        Dim Ajuda As String
        Ajuda = Application.StartupPath
        Ajuda = Ajuda.Replace("\bin\Debug", "")
        Ajuda = Ajuda & "\Arquivo de Ajuda\index.html#CadastroVeiculo"
        Dim Ie As Object
        Ie = CreateObject("InternetExplorer.Application")

        Ie.Visible = True
        Ie.Navigate(Ajuda)
    End Sub

    Private Sub bSair_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bSair.Click
        Me.Close()
    End Sub

    Private Sub bClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bClose.Click
        gbConsulta.Visible = False
        Me.Location = New System.Drawing.Point(Me.Location.X, Me.Location.Y + 127)
        Me.Size = New Size(734, 304)
    End Sub

    Private Sub bFiltrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bFiltrar.Click
        atualizaGrid()
    End Sub
#End Region

    Private Sub bmarca_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bmarca.Click
        Try
            Dim frm As New frm_consultas
            objBLLMarcas = New MarcasBLL
            frm.tipo = "marcas"
            frm.ShowDialog()
            If (frm.codigo <> 0) Then
                objBLLMarcas.localizar(frm.codigo)
                tbcodmarca.Text = objBLLMarcas.pMar_codigo
                tbmarca.Text = objBLLMarcas.pMar_nome
                objBLLMarcas = Nothing
            End If
            frm = Nothing
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Erro")
        End Try
    End Sub

    Private Sub bmodelo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bmodelo.Click
        Try
            Dim frm As New frm_consultas
            objBLLModeos = New ModelosBLL
            frm.tipo = "modelos"
            frm.numero = tbcodmarca.Text
            frm.ShowDialog()
            If (frm.codigo <> 0) Then
                objBLLModeos.localizar(frm.codigo)
                tbcodmodelo.Text = objBLLModeos.pMod_codigo
                tbmodelo.Text = objBLLModeos.pMod_nome
                objBLLModeos = Nothing
            End If
            frm = Nothing
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Erro")
        End Try
    End Sub

    Private Sub bcombustivel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bcombustivel.Click
        Try
            Dim frm As New frm_consultas
            objBLLCombustivel = New CombustivelBLL
            frm.tipo = "combustivel"
            frm.ShowDialog()
            If (frm.codigo <> 0) Then
                objBLLCombustivel.localizar(frm.codigo)
                tbcodcombustivel.Text = objBLLCombustivel.pCodigo
                tbcombustivel.Text = objBLLCombustivel.ptipo
                objBLLMarcas = Nothing
            End If
            frm = Nothing
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Erro")
        End Try
    End Sub

    Private Sub cbstatus_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbstatus.SelectedIndexChanged

    End Sub

    Private Sub tbcapacidade_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tbcapacidade.KeyPress
        If Asc(e.KeyChar) = 3 Or Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 22 Or Asc(e.KeyChar) = 24 Or Asc(e.KeyChar) = 44 Then
            Exit Sub
        End If

        If Not Char.IsNumber(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

    Private Sub tbcapacidade_Leave(sender As System.Object, e As System.EventArgs) Handles tbcapacidade.Leave
        If (tbcapacidade.Text <> "") Then
            tbcapacidade.Text = FormatNumber(tbcapacidade.Text, 0)

            If (tbcapacidade.Text = 0) Then
                MsgBox("Valor deve ser maior que zero!", MsgBoxStyle.Exclamation, "Alerta")
                tbcapacidade.Text = ""
            End If
        End If
    End Sub

    Private Sub TBanofab_Leave(sender As System.Object, e As System.EventArgs) Handles TBanofab.Leave
        If (TBanofab.Text <> "") Then
            TBanofab.Text = FormatNumber(TBanofab.Text, 0)

            If (TBanofab.Text = 0) Then
                MsgBox("Valor deve ser maior que zero!", MsgBoxStyle.Exclamation, "Alerta")
                TBanofab.Text = ""
            End If
        End If
    End Sub

    Private Sub TBanofab_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TBanofab.KeyPress
        If Asc(e.KeyChar) = 3 Or Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 22 Or Asc(e.KeyChar) = 24 Or Asc(e.KeyChar) = 44 Then
            Exit Sub
        End If

        If Not Char.IsNumber(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

    Private Sub tbanomod_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tbanomod.KeyPress
        If Asc(e.KeyChar) = 3 Or Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 22 Or Asc(e.KeyChar) = 24 Or Asc(e.KeyChar) = 44 Then
            Exit Sub
        End If

        If Not Char.IsNumber(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

    Private Sub tbanomod_Leave(sender As System.Object, e As System.EventArgs) Handles tbanomod.Leave
        If (tbanomod.Text <> "") Then
            tbanomod.Text = FormatNumber(tbanomod.Text, 0)

            If (tbanomod.Text = 0) Then
                MsgBox("Valor deve ser maior que zero!", MsgBoxStyle.Exclamation, "Alerta")
                tbanomod.Text = ""
            End If
        End If
    End Sub

    Private Sub dgDados_CellDoubleClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgDados.CellDoubleClick
        Dim codigo As Integer
        If (e.RowIndex >= 0) Then
            codigo = dgDados.Rows(e.RowIndex).Cells("vei_codigo").Value
            objBLL.localizar(codigo)
            If (objBLL.pcodVeiculo <> 0) Then
                carregaCampos()
                atual = objBLL.pcodVeiculo
                gbConsulta.Visible = False
                Me.Location = New System.Drawing.Point(Me.Location.X, Me.Location.Y + 127)
                Me.Size = New Size(737, 452)
            End If
        End If
    End Sub

    Private Sub badd_Click(sender As System.Object, e As System.EventArgs) Handles badd.Click
        Try

            cbCombustiveis.Items.Add(tbcombustivel.Text)
            tbcombustivel.Text = ""
            tbcodcombustivel.Text = ""
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        

    End Sub

    Private Sub bremover_Click(sender As System.Object, e As System.EventArgs) Handles bremover.Click
        cbCombustiveis.Text = ""
        If cbCombustiveis.SelectedIndex >= 0 Then
            cbCombustiveis.Items.RemoveAt(cbCombustiveis.SelectedIndex)
        Else
            MsgBox("Combustivel não selecionado")
        End If
    End Sub
End Class